package com.bsh.utils.system.smsApi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.bsh.utils.KeyValuePair;
import com.bsh.utils.system.SmsReponseMessage;

/**
 * 触发短信接口
 * 
 * @author gsh
 *
 */
@Component
@Lazy(false)
public class SmsApiCF implements ISmsApi {
	static String userCode;
	static String userPass;
	static String validCodeTpl;

	public static String getValidCodeTpl() {
		return validCodeTpl;
	}

	@Value("${sms.cf.valid_code_tpl}")
	void setValidCodeTpl(String validCodeTpl) throws UnsupportedEncodingException {
		String str = new String(validCodeTpl.getBytes("ISO-8859-1"), "utf-8");
		SmsApiCF.validCodeTpl = str;
	}

	public static String getUserCode() {
		return userCode;
	}

	@Value("${sms.cf.user_code}")
	public void setUserCode(String userCode) {
		SmsApiCF.userCode = userCode;
	}

	public static String getUserPass() {
		return userPass;
	}

	@Value("${sms.cf.user_pass}")
	public void setUserPass(String userPass) {
		SmsApiCF.userPass = userPass;
	}

	/**
	 * 发送验证码
	 *
	 * {"http_status_code":400,"code":5,"msg":"未找到匹配的模板","detail":"未自动匹配到合适的模板"}
	 */
	@Override
	public SmsReponseMessage sendValidCode(String mobile, String validCode) {
		String res = send(mobile, validCode);
		SmsReponseMessage msg = new SmsReponseMessage();
		KeyValuePair<String, String> kp = CfSmsXmlResultParser.parse(res);
		msg.setCode(Integer.parseInt(kp.getKey()));
		msg.setMsg(kp.getValue());
		msg.setMobile(mobile);
		return msg;
	}

	private static String send(String mobile, String validCode) {
		String url = "http://h.1069106.com:1210/Services/MsgSend.asmx/SendMsg";

		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("userCode", SmsApiCF.getUserCode()));
		nvps.add(new BasicNameValuePair("userPass", SmsApiCF.getUserPass()));
		nvps.add(new BasicNameValuePair("DesNo", mobile));
		nvps.add(new BasicNameValuePair("Msg", String.format(SmsApiCF.getValidCodeTpl(), validCode)));
		nvps.add(new BasicNameValuePair("Channel", "0"));
		String msg = httpPost(url, nvps); // post请求

		// String getparam =
		// "userCode=用户名&userPass=密码&DesNo=手机号&msg=短信内容【签名】&Channel=0";
		// String result = httpGet(url, getparam); // get请求

		return msg;
	}

	public static String httpPost(String url, List<NameValuePair> params) {
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instreams = entity.getContent();
				result = convertStreamToString(instreams);
			}
		} catch (Exception e) {
		}
		return result;
	}

	private static String httpGet(String url, String params) {
		String result = "";
		try {
			HttpClient client = new DefaultHttpClient();
			if (params != "") {
				url = url + "?" + params;
			}
			HttpGet httpget = new HttpGet(url);
			HttpResponse response = client.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instreams = entity.getContent();
				result = convertStreamToString(instreams);
			}
		} catch (Exception e) {
		}
		return result;
	}

	private static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

}
